/*
 *  FontSerialiser.cpp
 *
 *  Created by David Rowland on 24/11/2008.
 *  Copyright 2008 UWE. All rights reserved.
 *	Code derived from Font Serialiser by Niall Moody
 *
 */

#include <juce/juce.h>
#include "TextConsole.h"

File serialiseFont(String filename, String fontname, File outputDirectory, TextConsole* &textConsole)
{
	textConsole->addLine("\n\n--------------------------------\n Font Serialiser by Niall Moody\n--------------------------------\n");
	
	/* Check to see if temp file allready exists
	   This needs to be done otherwise the data will just
	   be appended to the file and give an invalid font  */
	if( outputDirectory.getChildFile(filename).existsAsFile() )
	{
		textConsole->addLine( String("***Font file already exists, \nPlease choose a different file name, location or delete the file") );
		return File::nonexistent;
	}
	else
	{
		// Create temp font file
		const File destFile = outputDirectory.getChildFile(filename).getNonexistentSibling(true);
		textConsole->addLine( String("Destination Directory: ") << destFile.getFullPathName() );	
		
		String FontName(fontname);
		
		OutputStream *fontfile = destFile.createOutputStream();
		
		if (fontfile == 0)
		{
			String error ("\nError : Couldn't open ");
			error << destFile.getFullPathName() << " for writing.\n\n";
			textConsole->addLine((const char*) error);
		}
		
		Typeface *font = 0;
		font = new Typeface(FontName, false, false);
		if(!font)
		{
			String error ("\nError : could not find font.\n\n");
			textConsole->addLine((const char*) error);
		}
		
		// Retrieve glyphs from system font
		for(int i=0;i<256;++i)
			font->getGlyph(i);
		
		String op("\nWrote font ");
		op << FontName << " to file " << destFile.getFullPathName() << " successfully.\n";
		textConsole->addLine((const char *)op);
		
		font->serialise(*fontfile);
		
		delete font;
		delete fontfile;
			
		return destFile;
	}
}